#!/usr/bin/env python
#
#       Database.py
#       
#       Copyright 2009 Robin Hayes <bonzairob@hotmail.co.uk>
#       Copyright 2009 Ben Davis <its.hip@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import hashlib
import pygame
import urllib

from Interfaces import TimedBox, BackButton
import Options

class Database:
    def __init__(self):
        #Doesn't need to be loaded at startup yet really but meh.
        #Maybe later for keeping track of TS games.
        self.game = "TurnShipDemo"
        self.loggedin = False
        if Options.AUTOLOGIN == True:
            if Options.USERNAME and Options.PASSWORD:
                self.login(Options.USERNAME, Options.PASSWORD)
        
    def login(self, username, password):
        try:
            self.username = username
            self.password = password

            urlparams = urllib.urlencode({'username': self.username, 'katamari': hashlib.sha1(self.username.lower() + self.password).hexdigest(), 'game': self.game})
            urlf = urllib.urlopen("http://pandrgames.co.uk/dbmanip/login.php", urlparams)
            self.loggedin = True
            return urlf.read()
        except IOError:
            self.loggedin = False
            return
            
    def loginbynum(self, widgetcont, username, password, remember):
        try:
            urlparams = urllib.urlencode({'username': username, 'katamari': hashlib.sha1(username.lower() + password).hexdigest(), 'game': self.game})
            urlf = urllib.urlopen("http://pandrgames.co.uk/dbmanip/login.php?num=true", urlparams)
            self.loggedin = True
            code = urlf.read()
            if code == "0":
                widgetcont.pop(len(widgetcont)-1)
                widgetcont.append(TimedBox(widgetcont, "You are logged in."))
                widgetcont.append(BackButton(widgetcont, "self.parent.parent.parent.main()"))
                self.username = username
                self.password = password
                #if remember True, write to options.
            elif code == "1":
                widgetcont.append(TimedBox(widgetcont, "Username or password incorrect."))
            else:
                widgetcont.append(TimedBox(widgetcont, "Error, sorry =C"))
        except IOError:
            self.loggedin = False
            widgetcont.append(TimedBox(widgetcont, "Error, sorry =C"))
            return
    
    def logout(self):
        try:
            if self.loggedin:
                urlparams = urllib.urlencode({'username': self.username, 'game': self.game})
                urlf = urllib.urlopen("http://pandrgames.co.uk/dbmanip/login.php", urlparams)
                return urlf.read()
        except IOError:
            return
    
    def server_list(self):
        try:
            data = urllib.urlopen("http://pandrgames.co.uk/dbmanip/tsgames.php").read()
            servers = []
            for server in data.split("&"):
                if server:
                    username, hasaccount, address, port, users, map, notes = server.split(":")
                    if users.count(";") > 0:
                        users = users.split(";")
                    else:
                        users = [users]
                    for user in users[:]:
                        if user == "":
                            users.remove(user)
                    servers.append({'username':username, 'hasaccount':hasaccount, 'address':address, 'port':port, 'users':users, 'map':map, 'notes':notes})
            return servers
        except IOError:
            return False
